<template>
	<div class="release">
		<van-nav-bar color="#1365b7" left-arrow @click-left="onClickLeft" @click-right="onClickRight">
		</van-nav-bar>
		<van-form @submit="onSubmit">
		    <van-cell-group inset>
				<van-field
					v-model="message"
					rows="10"
					autosize
					type="textarea"
					maxlength="100"
					placeholder="分享新鲜事..."
					show-word-limit
				/>
				<van-field name="uploader">
					<template #input>
					    <van-uploader v-model="fileList" multiple />
					</template>
				</van-field>
		    </van-cell-group>
		</van-form>
		<div>
			<van-button type="success" size="small" color="#1365b7"> 发表 </van-button>
		</div>
	</div>
</template>

<script>
	
	import { Toast } from "vant"
	import { uploadImg, releaseGraphic } from '../../request/api/socialApi.js'
	import { getCurrentTime } from '../../utils/index.js'
	
	export default {
		name: 'release',
		data() {
			return {
				message: '',
				fileList: [],
				imgUrlList: [],
			}
		},
		methods: {
			// 返回
			onClickLeft() {
				this.$router.push({path:'/social'})
			},
			// 发表
			onClickRight() {
				if (this.message || this.fileList.length) {
					this.onSubmit()
				}
				Toast({
					message: '请输入内容',
					icon: 'warning-o',
				})
			},
			// 提交,先上传图片拿到url,再提交
			onSubmit() {
				Toast.loading({
					duration: 0, // 持续展示 Toast
					message: '发布中...',
					forbidClick: true,
				})
				let files = this.fileList
				let formdata = new FormData()
				files.map(i => {
					formdata.append('file', i.file)
				})	
				uploadImg(formdata).then(res => {
					if (res.data) {
						this.imgUrlList = res.data.map(i => {
							return i.imgPath
						})
					}
					const obj = {
						id: this.$uid(),
						userImg: "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.zhimg.com%2Fv2-d1e899516430480f57da34fd34891f18_1440w.jpg%3Fsource%3D172ae18b&refer=http%3A%2F%2Fpic1.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1651936035&t=a129504ab1ae5e6437a4ce6247f1c86e",
						userName: "王二狗",
						content: this.message,
						fileUrl: this.imgUrlList,
						like: '18', // 点赞
						addTime: getCurrentTime()
					}
					releaseGraphic(obj).then(res => {
						if (res.data) {
						    if (res.data.code == 0) {
						        Toast({
									message: '发表成功',
									icon: 'success',
									// color: '#07C160'
								})
						        this.$router.push({path:'/social'})
						    }
						} else {
						    Toast({
						    	message: '发表失败',
						    	icon: 'cross',
								// color: '#EE0A24'
						    })
						}
					})
				}).catch()
			}
		},
	}
</script>

<style lang="scss" scoped>
	.release {
		position: fixed;
		top: 0;
		left: 0;
		bottom: 0;
		right: 0;
		height: 100%;
		z-index: 99;
		.van-form {
			height: 100%;
			.van-cell-group {
				height: 100%;
				margin: 0;
			}
		}
	}
</style>